<?php
namespace app\common\controller;

use think\Controller;
use think\Session;
use app\common\model\MemberModel;
use web\util\WechatUtil;
use think\Request;

/**
 * 前台基类
 *
 * @author jinxiwang
 *        
 */
class Base extends Controller {

    /**
     * 登录标识
     *
     * @var string
     */
    const LOGIN_KEY = 'USER_KEY';

    /**
     * 析构函数
     */
    public function __construct() {
        parent::__construct();
        
    }

    /*
     * 初始化操作
     */
    public function _initialize() {
        //判断是否是微信
        $mid = $this->getLoginId();
        if(!Request::instance()->isAjax()){//不是接口时,要微信授权和绑定微信
            if(empty($mid)){
                if(is_weixin()){
                    //查询 有没有绑定,没有绑定就用账号秘密登录
                    $passportUid = WechatUtil::getPassportUid();
                    if($passportUid){
                        $member = MemberModel::instance()->getLoginByPassportUid($passportUid);
                        if($member){
                            $this->putLoginInfo($member['id']);
                        }
                    }
                }
            }else{
                $passportUid = WechatUtil::getPassportUidFromSession();
                
            }
        }
    }

    /**
     * 返回前端信息
     *
     * @param int $code
     * @param string $msg
     * @param string $data
     * @return \think\response\Json
     */
    protected function returnResult($code, $msg = '', $data = '') {
        return json([
            "returnCode" => $code,
            "returnMsg" => $msg,
            "data" => $data
        ]);
    }

    /**
     * 获取登录信息
     *
     * @return number
     */
    protected function getLoginId() {
        return session::get(self::LOGIN_KEY);
    }

    /**
     * 清除登录信息
     */
    protected function clearLogin() {
        session::delete(self::LOGIN_KEY);
    }

    /**
     * 设置登录信息
     *
     * @param number $mid
     */
    protected function putLoginInfo($mid) {
        session(self::LOGIN_KEY, $mid);
    }

    /**
     * 判断登录
     * @return \think\response\Json|void
     */
    protected function needLogin() {
        $mid = $this->getLoginId();
        if(empty($mid)){
            if($this->request->isAjax()){
                $this->returnResult(-7,'未登录')->send();
                exit;
            }else{
                return $this->redirect('/mobile/index/login');
            }
        }
        
    }
}